require 'json'
require 'spoule/auth'
require 'spoule/json'
require 'spoule/parameter'

module Spoule
  class Method
    class Base
      include Spoule::Json

      attr_accessor :description, :request, :response, :media_upload

      def initialize(http_method, name, id, path)
        @http_method = http_method
        @name = name
        @id = id
        @path = path
        
        @parameters = []
        @auths = []
      end

      def <<(o)
        case o
        when Spoule::Auth
          @auths << o
        when Spoule::Parameter::Base
          @parameters << o
        else
          raise "Cannot accept objects of type #{o.class}!"
        end
      end

      def to_json(*opts)
        s  = ''
        s += _format_json_prefix(@name, opts)
        s += _format_json_kvp('id', @id, opts)
        s += ',' + _format_json_kvp('path', @path, opts)
        s += ',' + _format_json_kvp('httpMethod', @http_method, opts)
        s += ',' + _format_json_kvp('description', @description, opts)
        s += ',' + _format_json_prefix('parameters', opts)
        s += @parameters.inject([]) {|a,x| a << x.to_json(opts) }.join(',')
        s += _format_json_suffix # } parameters
        s += ',' + _format_json_array('parameterOrder', @parameters.collect{|x| x.name}, opts)

        if !request.nil?
          s += ',' + _format_json_prefix('request', opts)
          s += _format_json_kvp('$ref', request, opts)
          s += _format_json_suffix
        end

        if !response.nil?
          s += ',' + _format_json_prefix('response', opts)
          s += _format_json_kvp('$ref', response, opts)
          s += _format_json_suffix
        end

        if @auths.size > 0
          s += ',' + _format_json_array('scopes', @auths.collect{|x| x.url}, opts)
        end

        if !media_upload.nil?
          s += ',' + media_upload.to_json(opts)
        end

        s += _format_json_suffix # } @name
        return s
      end
    end

    class HttpDelete < Base
      def initialize(*args)
        super('DELETE', *args)
      end
    end

    class HttpGet < Base
      def initialize(*args)
        super('GET', *args)
      end
    end

    class HttpPatch < Base
      def initialize(*args)
        super('PATCH', *args)
      end
    end

    class HttpPost < Base
      def initialize(*args)
        super('POST', *args)
      end
    end

    class HttpPut < Base
      def initialize(*args)
        super('PUT', *args)
      end
    end
  end
end # module Spoule
